/**
 * @Project Name :  als-rpc-client
 * @Package Name :  com.alvis.transfer
 * @Description :  TODO
 * @author :  Alvis
 * @Creation Date:  2018-07-04 11:52 AM
 * @ModificationHistory Who    When    What
 * --------  ---------  --------------------------
 */
package com.alvis.transfer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author :  Alvis
 * @Description :  TODO
 * @Creation Date:  2018-07-04 11:52 AM
 */
public class RpcClient {
    private final static Logger logger = LoggerFactory.getLogger(RpcClient.class);

    public RpcClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private String host;
    private int port;

    public RpcResponse request(RpcRequest content) {
        RpcTransfer nettyTransfer = new RpcTransfer();
        nettyTransfer.setRequest(content);
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ClientChannelHandler(nettyTransfer));
        try {
            ChannelFuture f = bootstrap.connect(host, port).sync();
            logger.info("rpc client start request");
            f.channel().closeFuture().sync();
            return nettyTransfer.getResponse();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
